package com.yc.jpyy.utils;

import java.io.IOException;
import java.sql.Date;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


@Service
public class Tools {
	/**
	 * json转Map Key为小写字母
	 * 
	 * @author dhr
	 * @param json
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> JsonToMap(String json) {
		Map<String, Object> map = null;
		ObjectMapper objectMapper = new ObjectMapper();
		Map<String, Object> resultMap = new HashMap<>();
		String rex = "/Date[(](.*?)[)]/";
		Date longDate = null;
		Pattern pattern = null;
		Matcher m = null;
		try {
			map = objectMapper.readValue(json, HashMap.class);
         } catch (IOException e) {
			e.printStackTrace();
		}
        //遍历MAP得到所需要的数据
		for (String key : map.keySet()) {
			//JSONDate格式化
			if (map.get(key) != null) {
				pattern = Pattern.compile(rex);
				m = pattern.matcher(map.get(key).toString());
				if (m.find()) {
					String str = m.group(1);
					longDate = new Date(Long.parseLong(str));
					DateFormat df = DateFormat.getDateTimeInstance();//20180725修改可以精确到时分秒
					map.put(key, df.format(longDate));

				}
			}
            //格式化键
			String newKey = key.toLowerCase();
			newKey = newKey.replace("_", "");
			resultMap.put(newKey, map.get(key));
		}

		return resultMap;
	}

	/**
	 * json转List
	 * 
	 * @author dhr
	 * @param json
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List<Map<String, Object>> JsonTolist(String json) {
		ObjectMapper mapper = new ObjectMapper();
		List<Map<String, Object>> list = null;
		try {
			// mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
			list = mapper.readValue(json, ArrayList.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 字符串按逗号分隔为List
	 * 
	 * @author dhr
	 * @param Strings
	 * @return
	 */
	public static List<String> handleString(String Strings) {
		if (StringUtils.isEmpty(Strings)) {
			return null;
		}
		List<String> list = new ArrayList<>();
		String[] strs = Strings.split(",");
		for (String str : strs) {
			list.add(str);
		}
		return list;
	}

	public static boolean checkParams(String... params) {
		for (int i = 0; i < params.length; i++) {
			if (!isNotEmpty(params[i])) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 检查字符串中是否有空字符串
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNotEmpty(Object str) {
		if (str == null || "".equals(str) || "null".equals(str)) {
			return false;
		}
		return true;
	}
	
	 public static String requestCalendar( String httpArg) {
	        String httpUrl="http://www.easybots.cn/api/holiday.php";
	        BufferedReader reader = null;
	        String result = new String();
	        StringBuffer sbf = new StringBuffer();
	        httpUrl = httpUrl + "?m=" + httpArg;

	        try {
	            URL url = new URL(httpUrl);
	            HttpURLConnection connection = (HttpURLConnection) url
	                    .openConnection();
	            connection.setRequestMethod("GET");
	            connection.connect();
	            InputStream is = connection.getInputStream();
	            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	            String strRead = null;
	            while ((strRead = reader.readLine()) != null) {
	                sbf.append(strRead);
	                //sbf.append("\r\n");
	            }
	            reader.close();
	            result = sbf.toString();
	           // Map<String,Object> map=JsonUtil.toMap(result);
	            //String res=(String)map.get(httpArg);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        return result;
	    }
	 /*
	  * 聚合数据获取节假日期集合
	  */
	 public static List<String> getHolidayByYear(int year) {
	        String httpUrl="http://v.juhe.cn/calendar/year";
	        BufferedReader reader = null;
	        String results = new String();
	        StringBuffer sbf = new StringBuffer();
	        httpUrl = httpUrl + "?year=" + String.valueOf(year) + 
	        		  "&key=a1b6c91376e3238ec4a22866457468a5";
	        List<String> holidayList = new ArrayList<>();
	        try {
	            URL url = new URL(httpUrl);
	            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	            connection.setRequestMethod("GET");
	            connection.connect();
	            InputStream is = connection.getInputStream();
	            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	            String strRead = null;
	            while ((strRead = reader.readLine()) != null) {
	                sbf.append(strRead);
	            }
	            reader.close();
	            results = sbf.toString();
	            //获取结果中的日期集合
	            JSONObject jsonObject1 = JSONObject.fromObject(results);
	            String result = jsonObject1.getString("result");
	            JSONObject jsonObject2 = JSONObject.fromObject(result);
	            String data = jsonObject2.getString("data");
	            JSONObject jsonObject3 = JSONObject.fromObject(data);
	            JSONArray holiday_list = jsonObject3.getJSONArray("holiday_list");
	            for (int i = 0; i < holiday_list.size(); i++) {
	            	//日期格式如：2018-1-1
	                String date = holiday_list.getJSONObject(i).getString("startday");
	                String month = date.substring(date.indexOf("-") + 1,date.lastIndexOf("-"));
	                String day = date.substring(date.lastIndexOf("-")+1);
	                date = String.valueOf(year) + "-" +
	                		(Integer.valueOf(month)<10 ? "0" + month : month) + "-" +
	                	    (Integer.valueOf(day)<10 ? "0" + day : day);
	                holidayList.add(date);
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        return holidayList;
	    }

	

	public static void main(String[] args) {
		//String str = "{\"ID\":null,\"ManageOrganizationOrganizationCoding\":\"Y\",\"ManageOrganization\":\"\",\"CompanyName\":\"测试公司\",\"CompanySimple\":\"公司简称\",\"CompanyAddress\":\"地址\",\"EconomicType\":\"个体\",\"LicenseNum\":\"1232443232423423\",\"LicenseBeginDate\":\"\\/Date(1531101158666)\\/\"}";
        //String info = " {\"dbcode\":\"A1\",\"PgName\":\"aaaa\",\"Industry\":\"1\",\"items\":[{\"a1\": \"11\",\"name1\":\"lihong\"},{\"a2\": \"22\",\"name2\":\"lihong2\"}]}";
         
		//System.out.println(JsonToMap(info));
		//JSONObject jsonObject = JSONObject.fromObject(info);
		
		//获取JSON对象中的JSON对象数组
		//JSONArray jsonArray = jsonObject.getJSONArray("items");
        //System.out.println(jsonArray);
        //int jsonArraySize = jsonArray.size();//获取数组长度
       // for(int i = 0; i < jsonArraySize; i++ ){
			//JSON对象转JSON字符串
			//String str = jsonArray.getJSONObject(i).toString();
			//JSON字符串转map
			//Map<String,Object> paramsMaps = Tools.JsonToMap(str);
			//System.out.println(paramsMaps);
		//}
		
		
		 String aa = "/Date(1531101158666)/";

		

	}
}
